package com.keyidea.jfxui.core.config.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 功能描述：Redis 配置
 */
@Configuration
public class RedisConfiguration {

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer result = new RedisMessageListenerContainer();
        result.setConnectionFactory(redisConnectionFactory);

        return result;
    }

    @Bean("redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> result = new RedisTemplate<>();
        result.setConnectionFactory(factory);

        result.setKeySerializer(stringRedisSerializer());
        result.setHashKeySerializer(stringRedisSerializer());

        result.setValueSerializer(stringRedisSerializer());
        result.setHashValueSerializer(stringRedisSerializer());
        return result;
    }


    @Bean("redisTemplateByte")
    public RedisTemplate<String, byte[]> redisTemplateByte(RedisConnectionFactory factory) {
        RedisTemplate<String, byte[]> result = new RedisTemplate<>();
        result.setConnectionFactory(factory);

        result.setKeySerializer(stringRedisSerializer());
        result.setValueSerializer(new RedisSerializer<>() {

            @Override
            public byte[] serialize(Object value) throws SerializationException {
                return (byte[]) value;
            }

            @Override
            public Object deserialize(byte[] bytes) throws SerializationException {
                return bytes;
            }
        });
        return result;
    }

    @Bean
    public PrintMessageListener printMessageListener() {
        return new PrintMessageListener(stringRedisSerializer());
    }

    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }
}
